package com.springSecurity.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class securityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 授权
     * @param http the {@link HttpSecurity} to modify
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问 功能页面只有有权限的才可以
        //请求授权规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1").hasRole("vip1")
                .antMatchers("/level2").hasRole("vip2")
                .antMatchers("level3/**").hasRole("vip3");

        //没有权限进入登录页
        http.formLogin();
        //定制登录页
//        http.formLogin().loginPage("/login");
        //防止网站攻击 关闭
        http.csrf().disable();
        //注销 开启注销
        http.logout();
        //注销成功后跳转
//        http.logout().logoutSuccessUrl("/");
//        http.httpBasic();
        //记住我功能
        http.rememberMe();
        //定制
//        http.rememberMe().rememberMeParameter("rememberMe");
    }

    /**
     * 认证
     * @param auth the {@link AuthenticationManagerBuilder} to use
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("vip1", "vip2")
                .and()
                .withUser("user").password(new BCryptPasswordEncoder().encode("user")).roles("vip1", "vip2","vip3")
                .and()
                .withUser("user2").password(new BCryptPasswordEncoder().encode("user2")).roles("vip1");

    }
}
